package com.my_library_one.mybase;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.gyf.barlibrary.ImmersionBar;
import com.my_library_one.http.AnsynHttpRequest;
import com.my_library_one.util.ActivityManager;
import com.my_library_one.util.KeyBoardUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity implements AnsynHttpRequest.ObserverCallBack {

    protected Handler mHandler = new Handler(Looper.getMainLooper());
    private Unbinder unbinder;
    protected ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(setLayoutId()>0){
            setContentView(setLayoutId());
        }
        //初始化沉浸式
        if (isImmersionBarEnabled())
            initImmersionBar();
        ActivityManager.getInstance().addActivity(this);
        //绑定控件
        unbinder = ButterKnife.bind(this);
    }

    /**
     * 设置布局layout
     * @return
     */
    protected abstract int setLayoutId();
    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    protected void onStop() {
        KeyBoardUtil.hideSoftKeyboard(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        OkHttpUtils.getInstance().cancelTag(this);
        ActivityManager.getInstance().removeActivity(this);
        unbinder.unbind();
        mHandler = null;
        mImmersionBar = null;
        super.onDestroy();
    }

    @Override
    public Resources getResources() {
        //当修改系统字体大小后，可以使App内字体大小保持不变
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 接口请求成功
     * @param data     返回的数据 json
     * @param method   判断是哪个接口返回的数据
     */
    @Override
    public void sucessResponse(String data, int method) {}
    /**
     * 接口请求失败
     * @param error
     * @param method   判断是哪个接口返回的数据
     */
    @Override
    public void failedResponse(String error, int method) {}
    /**
     * 无网络
     * @param error
     * @param method   判断是哪个接口返回的数据
     */
    @Override
    public void networkResponse(String error, int method) {}
}
